﻿package net.wangit.view.tree;

import java.util.List;

import net.wangit.support.TreeWriter;
import net.wangit.util.Checker;


public class StaticTreeWriter implements TreeWriter {

	private static final String BLANK = "<span></span>";
	private TreeConfig config;
	private String checkboxName;

	public StaticTreeWriter() {
		checkboxName = "";
	}

	public String write(Tree tree) {
		config = tree.getConfig();
		checkboxName = config.getDivAttribute();
		StringBuffer html = new StringBuffer("<div id=_statictree class=tree>");
		write(tree, html, 0, tree.getId());
		html.append("</div>");
		return html.toString();
	}

	private void write(Tree tree, StringBuffer html, int tab, String parentId) {
		String id = tree.getId();
		html.append("<div id=\"").append(id).append("\">");
		for (int i = 0; i < tab; i++)
			html.append(StaticTreeWriter.BLANK);

		html.append("<img class=ic src=\"").append(tree.getIcon())
				.append("\">");
		if (config.isSupportCheck()) {
			html.append("<input id=\"").append(parentId).append(
					"\" type=checkbox class=cc name=").append(checkboxName)
					.append(" value=\"").append(tree.getCheckValue()).append(
							"\"");
			String checkAttribute = tree.getCheckAttribute();
			if (!Checker.isEmpty(checkAttribute))
				html.append(" ").append(checkAttribute);
			html.append("/>");
		}
		String attribute = tree.getAttribute();
		if (!Checker.isEmpty(attribute))
			html.append(attribute);
		html.append("<a unselectable=on>").append(tree.getName())
				.append("</a>");
		html.append("</div>");
		List<Tree> leafs = tree.getLeafs();
		if (leafs != null) {
			int leafTab = tab + 1;
			for (int i = 0; i < leafs.size(); i++)
				write(leafs.get(i), html, leafTab, id);

		}
	}
}
